<template>
  <border title="通信" :close="true" w="350px" h="200px" @close="$emit('close')" x="41%" y="14%">
    <div class="msgPages">
      <!-- 左侧联系人列表 -->
<!--      <div class="left">-->
<!--        <div class="search">-->
<!--          <el-input placeholder="搜索联系人" prefix-icon="el-icon-search" v-model="searchText" clearable>-->
<!--          </el-input>-->
<!--        </div>-->
<!--        <div class="contact-list">-->
<!--          <div-->
<!--            v-for="contact in filteredContacts"-->
<!--            :key="contact.groupName"-->
<!--            class="row"-->
<!--            :class="{ 'row_select': currentChat && currentChat.groupName === contact.groupName }"-->
<!--            @click="selectContact(contact)"-->
<!--          >-->
<!--            <i class="el-icon-user-solid icons"/>-->
<!--            <div class="center">-->
<!--              <div class="h">-->
<!--                <span>{{ contact.groupRealname }}</span>-->
<!--              </div>-->
<!--              <div class="chat-type-tag">-->
<!--                {{ contact.groupType === 'person' ? '个人' : '群组' }}-->
<!--              </div>-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->
<!--      </div>-->

      <!-- 右侧聊天区域 -->
      <div class="right" >
        <div class="chat-header">
          <div class="chat-info">
<!--            <i class="el-icon-user-solid header-icon"/>-->
<!--            <span class="chat-name">{{ currentChat.groupRealname }}</span>-->
<!--            <span class="chat-type">{{ currentChat.groupType === 'person' ? '个人' : '群组' }}</span>-->
          </div>
        </div>

        <!-- 消息发送区域 -->
        <div class="message-send-area">
          <div class="send-container">
            <el-input
              type="textarea"
              :rows="8"
              placeholder="请输入要发送的消息内容..."
              v-model="msgTxt"
              resize="none"
              class="message-textarea"
            />
            <div class="send-actions">
              <div class="action-buttons">
                <el-button
                  type="primary"
                  @click="sendMessage"
                  :disabled="!msgTxt.trim() || sending"
                  :loading="sending"
                  class="send-btn"
                >
                  {{ sending ? '发送中...' : '发送消息' }}
                </el-button>
                <el-button @click="clearMessage" :disabled="!msgTxt.trim()">
                  清空
                </el-button>
              </div>
              <div class="message-tips">
                <i class="el-icon-info"></i>
<!--                消息将发送给: {{ currentChat.groupRealname }}-->
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 无选中聊天时的提示 -->
<!--      <div class="no-chat" v-else>-->
<!--        <div class="no-chat-content">-->
<!--          <i class="el-icon-chat-dot-round"></i>-->
<!--          <p>请选择一个联系人开始发送消息</p>-->
<!--          <p class="sub-tip">点击左侧联系人列表选择发送对象</p>-->
<!--        </div>-->
<!--      </div>-->
    </div>
  </border>
</template>

<script>
import border from "@/views/formShortLink/border/index.vue";
import {sendMessage, groupsPersons} from '@/api/message';
import {UserSettingInfo} from '@/api/permission/userSetting';

export default {
  name: "msgPage",
  props:['msgData','groupId'],
  components: {border},
  data() {
    return {
      // 当前用户信息
      currentUser: undefined,
      // 消息输入框内容
      msgTxt: '',
      // 搜索文本
      searchText: '',
      // 当前选中的聊天
      currentChat: null,
      // 联系人列表
      contacts: [],
      // 发送状态
      sending: false
    }
  },
  created() {
    this.getCurrentUserInfo();
    console.log(this.groupId,this.msgData)
  },
  computed: {
    // 过滤后的联系人列表
    filteredContacts() {
      if (!this.searchText) {
        return this.contacts;
      }
      return this.contacts.filter(contact =>
        contact.groupRealname.toLowerCase().includes(this.searchText.toLowerCase())
      );
    }
  },
  methods: {

    getCurrentUserInfo(){
      UserSettingInfo().then(res => {
        this.currentUser = res.data
        console.log(this.currentUser)
      })
    },

    // 选择联系人
    selectContact(contact) {
      this.currentChat = contact;
      this.msgTxt = '';
    },

    // 发送消息
    async sendMessage() {
      if (!this.msgTxt.trim()) {
        this.$message.warning('请输入消息内容');
        return;
      }


      this.sending = true;
      var toUserId = undefined;
      var type = undefined;
      var msg = this.msgTxt.trim();
      if (this.groupId === null && Array.isArray(this.msgData)  && this.msgData !== null) {
        for (var i = 0; i < this.msgData.length; i++){
          // 处理字符串情况
          type = 'person'
          toUserId = this.msgData[i].userId
          try {
            const request = {
              message: msg,
              type: type,
              fromUserId: this.currentUser.id,
              toUserId: toUserId
            };

            const response = await sendMessage(request);
            if (response.code === 200) {
              this.$message.success('消息发送成功');
              this.msgTxt = '';
            } else {
              this.$message.error('发送失败: ' + (response.message || '未知错误'));
            }
          } catch (error) {
            console.error('发送消息错误:', error);
            this.$message.error('发送失败，请重试');
          } finally {
            this.sending = false;
          }
        }

      }else if (this.groupId === null && typeof this.msgData === 'string'){
        type = 'person'
        toUserId = this.msgData
        try {
          const request = {
            message: this.msgTxt.trim(),
            type: type,
            fromUserId: this.currentUser.id,
            toUserId: toUserId
          };

          const response = await sendMessage(request);
          if (response.code === 200) {
            this.$message.success('消息发送成功');
            this.msgTxt = '';
          } else {
            this.$message.error('发送失败: ' + (response.message || '未知错误'));
          }
        } catch (error) {
          console.error('发送消息错误:', error);
          this.$message.error('发送失败，请重试');
        } finally {
          this.sending = false;
        }

      } if (this.groupId !== null) {
        type = 'group'
        toUserId = this.groupId
        try {
          const request = {
            message: this.msgTxt.trim(),
            type: type,
            fromUserId: this.currentUser.id,
            toUserId: toUserId
          };

          const response = await sendMessage(request);
          if (response.code === 200) {
            this.$message.success('消息发送成功');
            this.msgTxt = '';
          } else {
            this.$message.error('发送失败: ' + (response.message || '未知错误'));
          }
        } catch (error) {
          console.error('发送消息错误:', error);
          this.$message.error('发送失败，请重试');
        } finally {
          this.sending = false;
        }
      }

    },

    // 清空消息
    clearMessage() {
      this.msgTxt = '';
    },

    // 获取联系人列表
    getUserAndGroup() {
      groupsPersons().then(res => {
        if (res.code === 200) {
          this.contacts = res.data;
        } else {
          this.$message.error('获取联系人列表失败');
        }
      }).catch(error => {
        console.error('获取联系人错误:', error);
        this.$message.error('获取联系人列表失败');
      });
    }
  },
  mounted() {
    this.getUserAndGroup();
  }
}
</script>

<style scoped lang="scss">
.msgPages {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 100%;

  .left {
    width: 300px;
    border-right: 1px solid #DCDFE6;
    padding: 10px;
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .search {
      margin-bottom: 10px;
    }

    .contact-list {
      flex: 1;
      overflow-y: auto;

      .row {
        display: flex;
        flex-direction: row;
        padding: 12px 8px;
        border-radius: 8px;
        cursor: pointer;
        position: relative;
        transition: background-color 0.3s;
        margin-bottom: 2px;

        &:hover {
          background-color: #f5f7fa;
        }

        .icons {
          font-size: 36px;
          color: #409EFF;
          margin-right: 10px;
        }

        .center {
          display: flex;
          flex-direction: column;
          flex: 1;
          min-width: 0;

          .h {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 4px;

            span:first-child {
              font-weight: 600;
              font-size: 14px;
              color: #303133;
            }
          }

          .chat-type-tag {
            align-self: flex-start;
            background: #409EFF;
            color: white;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 11px;
            margin-top: 2px;
          }
        }
      }

      .row_select {
        background-color: #EBF6FF;

        &:hover {
          background-color: #EBF6FF;
        }
      }
    }
  }

  .right {
    display: flex;
    flex-direction: column;
    flex: 1;
    position: relative;
    height: 100%;

    .chat-header {
      padding: 12px 20px;
      border-bottom: 1px solid #DCDFE6;
      background: white;

      .chat-info {
        display: flex;
        align-items: center;

        .header-icon {
          font-size: 24px;
          color: #409EFF;
          margin-right: 8px;
        }

        .chat-name {
          font-weight: 600;
          font-size: 16px;
          margin-right: 8px;
        }

        .chat-type {
          background: #409EFF;
          color: white;
          padding: 2px 6px;
          border-radius: 4px;
          font-size: 12px;
        }
      }
    }

    .message-send-area {
      flex: 1;
      padding: 20px;
      background: #f5f7fa;
      display: flex;
      flex-direction: column;

      .send-container {
        background: white;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        height: 100%;
        display: flex;
        flex-direction: column;

        .message-textarea {
          flex: 1;

          ::v-deep .el-textarea__inner {
            border: none;
            font-size: 14px;
            line-height: 1.5;
            resize: none;
          }
        }

        .send-actions {
          margin-top: 15px;
          display: flex;
          justify-content: space-between;
          align-items: center;

          .action-buttons {
            .send-btn {
              min-width: 100px;
            }

            .el-button {
              margin-right: 10px;
            }
          }

          .message-tips {
            font-size: 12px;
            color: #909399;
            display: flex;
            align-items: center;

            i {
              margin-right: 5px;
              color: #409EFF;
            }
          }
        }
      }
    }
  }

  .no-chat {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f7fa;

    .no-chat-content {
      text-align: center;
      color: #909399;

      i {
        font-size: 64px;
        margin-bottom: 16px;
        display: block;
        color: #DCDFE6;
      }

      p {
        font-size: 16px;
        margin-bottom: 8px;
      }

      .sub-tip {
        font-size: 14px;
        color: #C0C4CC;
      }
    }
  }
}

// 滚动条样式
.contact-list::-webkit-scrollbar {
  width: 6px;
}

.contact-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.contact-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.contact-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
